/// 用户Provider
/// 管理用户、联系人列表和相关操作
library;
import 'package:flutter/material.dart';
import 'package:chat_project/models/user_model.dart';
import 'package:chat_project/services/api_service.dart';
import 'package:chat_project/services/storage_service.dart';

class UserProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  final StorageService _storageService = StorageService();
  
  List<User> _contacts = [];
  List<User> _searchResults = [];
  bool _isLoading = false;
  String? _error;
  
  // Getters
  List<User> get contacts => _contacts;
  List<User> get searchResults => _searchResults;
  bool get isLoading => _isLoading;
  String? get error => _error;
  
  // 初始化
  Future<void> init() async {
    await loadContacts();
  }
  
  // 加载联系人列表
  Future<void> loadContacts() async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();
      
      // 从API获取联系人列表
      final contactsData = await _apiService.getContacts();
      
      // 确保返回的数据不为空，并且是联系人列表
      _contacts = contactsData
          .where((contact) => contact != null && contact is Map<String, dynamic>)
          .map<User>((contact) {
            try {
              return User.fromJson(contact);
            } catch (e) {
              print('解析联系人数据失败: $e, 数据: $contact');
              return User(id: '', username: '未知用户', email: '');
            }
          })
          .where((user) => user.id.isNotEmpty) // 过滤掉无效用户
          .toList();
              
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      print('加载联系人失败: $e');
      _isLoading = false;
      _error = e.toString();
      // 确保在发生错误时清空联系人列表，不使用模拟数据
      _contacts = [];
      notifyListeners();
    }
  }
  
  // 清除错误
  void clearError() {
    _error = null;
    notifyListeners();
  }
  
  // 搜索用户
  Future<void> searchUsers(String keyword) async {
    if (keyword.isEmpty) {
      _searchResults = [];
      notifyListeners();
      return;
    }
    
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();
      
      print('搜索用户: $keyword');
      final results = await _apiService.searchUsers(keyword);
      print('搜索结果: ${results.length}个用户');
      
      _searchResults = results
          .map<User>((user) => User.fromJson(user))
          .toList();
      
      // 过滤掉已经是联系人的用户
      _searchResults = _searchResults.where((user) {
        return !_contacts.any((contact) => contact.id == user.id);
      }).toList();
      
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      print('搜索用户失败: $e');
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
    }
  }
  
  // 添加联系人
  Future<Map<String, dynamic>> addContact(String userId) async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();
      
      print('添加联系人: $userId');
      
      // 检查是否已经是联系人
      if (_contacts.any((contact) => contact.id == userId)) {
        _isLoading = false;
        _error = '该用户已经是您的联系人';
        notifyListeners();
        throw _error!;
      }
      
      // 调用添加联系人API
      final response = await _apiService.addContact(userId);
      print('添加联系人成功: $response');
      
      // 添加到联系人列表
      final newContact = User.fromJson(response['contact']);
      _contacts.add(newContact);
      
      // 从搜索结果中移除新添加的联系人
      _searchResults.removeWhere((user) => user.id == userId);
      
      _isLoading = false;
      notifyListeners();
      
      // 返回响应（包含联系人和对话信息）
      return response;
    } catch (e) {
      print('添加联系人失败: $e');
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
      rethrow;
    }
  }
  
  // 移除联系人
  Future<void> removeContact(String userId) async {
    try {
      _isLoading = true;
      notifyListeners();
      
      // 调用移除联系人API
      await _apiService.removeContact(userId);
      
      // 从联系人列表中移除
      _contacts.removeWhere((contact) => contact.id == userId);
      
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      print('移除联系人失败: $e');
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
    }
  }
  
  // 更新用户资料
  Future<void> updateProfile(Map<String, dynamic> data) async {
    try {
      _isLoading = true;
      notifyListeners();
      
      final updatedUser = await _apiService.updateUserProfile(data);
      print('更新用户资料成功: $updatedUser');
      
      // 更新本地存储的用户信息
      final currentUser = await _storageService.getUser();
      if (currentUser != null) {
        final updatedUserObj = User.fromJson(updatedUser);
        await _storageService.saveUser(updatedUserObj);
      }
      
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      print('更新用户资料失败: $e');
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
    }
  }
  
  // 更新头像
  Future<void> updateAvatar(String filePath) async {
    try {
      _isLoading = true;
      notifyListeners();
      
      final response = await _apiService.uploadAvatar(filePath);
      print('更新头像成功: $response');
      
      // 更新本地存储的用户信息
      final currentUser = await _storageService.getUser();
      if (currentUser != null && response['avatar'] != null) {
        final updatedUser = currentUser.copyWith(
          avatar: response['avatar'],
        );
        await _storageService.saveUser(updatedUser);
      }
      
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      print('更新头像失败: $e');
      _isLoading = false;
      _error = e.toString();
      notifyListeners();
    }
  }
} 